//
import { tool } from './js/assistant';
require('./css/reset.css');
require('./css/index.less');

const ajax = tool.ajax,
  $ = tool.$,
  $$ = tool.$$,
  eleAddEvent = tool.eleAddEvent,
  elesAddEvent = tool.elesAddEvent,
  addClass = tool.addClass,
  removeClass = tool.removeClass;
class gameSelector {
  /**
   * @param  {} id
   */
  constructor() {
    //这是从app native 传过来的
    this.userID = "5961d8e07a1ff9003265017e";
    this.isAndroid = false;
    this.isiOS = false;
    this.list = [];
    // [
    // { "gameName": "\u4e94\u5b50\u68cb", view: 10, "favorite": false, "describe": "\u4e24\u4e2a\u4eba\u73a9", "gameID": "5960c7d57a1ff9003264a684" },
    // { "gameName": "\u8c01\u662f\u5367\u5e95", "favorite": true, view: 20, "describe": "\u5927\u5bb6\u4e00\u8d77\u73a9", "gameID": "5960ccbd7a1ff9003264a72b" },
    // { "gameName": "巴拉巴拉1", "favorite": true, view: 15, "describe": "\u5927\u5bb6\u4e00\u8d77\u73a9", "gameID": "5960asd434h1ff9003264a72b" },
    // { "gameName": "巴拉巴拉2", "favorite": true,view:30,  "describe": "\u5927\u5bb6\u4e00\u8d77\u73a9", "gameID": "5960ccbd7a1fffyhnc54a72b"}

    // ];

  }

  init() {
    /**
     * 1. 返回箭头事件
     * 2. 分别选择推荐、收藏、排行榜事件
     * 3. 点击游戏技进行选择事件
     * 4. 收藏事件
     */
    //请求api 获取游戏列表
    $("#recommend").style.backgroundColor = "rgb(0, 188, 212)";
    $("#recommend").style.color = "#fff";
    if(platform()!=1){
      this.userID = this.getUserId();
    }
    
    ajax({
      url:'/mini/getGamesList?userID='+this.userID,
      method:'get',
      data:{},
    }).then((data)=>{
      console.log(JSON.parse(data));
      if(data.error){
        return;
      }
      this.list = JSON.parse(data).gameList;
      this.template(this.list); 
    }).catch((data)=>{
      console.log(data);
    })

    //构建游戏列表

    eleAddEvent($('#return'), 'click', () => {
      //返回客户端
    });

    eleAddEvent($('#game-ul'), 'click', (event) => {
      const target = event.target;
      const className = target.className;
      if (className === 'gameName') {
        const gameID = target.parentNode.dataset['id'];
        ajax({
          url: '/mini/clickGame?&gameID=' + gameID,
          method: 'get'
        }).then((data) => {
          if (!data['error']) {
            this.list.map((item)=>{
              if(item.gameID === gameID){
                item.view++;
                $('.game[data-id="'+gameID+'"] .rank-notice').innerHTML = '点击：'+ item.view;
              }
            })
            this.isAndroid && window.control.setResult(gameID);
            if(platform()==1){
              window.webkit.messageHandlers.chatfunios.postMessage({'gameid':1});
            }
          }
        })
        //给客户端返回相应的gameid
      } else if (className === 'collect') {
        //添加收藏
        const gameID = target.parentNode.dataset['id'];
        const isfavor = target.parentNode.dataset['favor'] === 'true' ? 1 : 0;
        !isfavor && ajax({
          url: '/mini/addFavorite?userID=' + userID + '&gameID=' + gameID,
          method: 'get'
        }).then((data) => {
          if (!data['error']) {
            target.parentNode.dataset['favor'] = 'true';
            this.list.map((item)=>{
              if(item.gameID === target.parentNode.dataset['id']){
                item.favorite = true;
              }
            })
          }
        })
        //删除收藏
        isfavor && ajax({
          url: '/mini/rmFavorite?userID=' + userID + '&gameID=' + gameID,
          method: 'get'
        }).then((data) => {
          if (!data['error']) {
            target.parentNode.dataset['favor'] = 'false';
            this.list.map((item)=>{
              if(item.gameID === target.parentNode.dataset['id']){
                item.favorite = false;
              }
            })
          }
        })
      }
    });
    elesAddEvent($$('.column'), 'click', (event) => {
      const id = event.target.id;
      for (let i = 0; i < $$('.column').length; i++) {
        $$('.column')[i].style.backgroundColor = $$('.column')[i].id === id ? "rgb(0, 188, 212)" : "#fff";
        $$('.column')[i].style.color = $$('.column')[i].id === id ? "#fff" : "rgb(93, 90, 90)";
      }
      switch (id) {
        case 'recommend':
          for (let i = 0; i < $$('.game').length; i++) {
            $$('.game')[i].style.display = 'block';
          }
          this.toggleDisplay(true);
          break;
        case 'collection':
          for (let i = 0; i < $$(".game[data-favor='false']").length; i++) {
            $$(".game[data-favor='false']")[i].style.display = 'none';
          }
          this.toggleDisplay(true);
          break;
        case 'rank':
          //先按照view字段进行排序，在重新渲染
          this.list.sort((a,b)=>{
            return a.view<b.view;
          })
          this.template(this.list);
          this.toggleDisplay(false);
          break;
        default:
          break;
      }

    })
  }
  template(gameList){
    var gameTemplate = "";
    for(var i=0;i<gameList.length;i++){
      gameTemplate += "<li class='game' data-id='"+gameList[i].gameID+"' data-favor='"+gameList[i].favorite+"'><div class='gameName'>"+gameList[i].gameName+"</div><div class='collect'></div><div class='rank-notice disappear'>点击："+gameList[i].view+"</div></li>";
    }
    $("#game-ul").innerHTML = (gameTemplate);
  }
  //显示收藏按钮还是点击量

  toggleDisplay(isCollect){
    if(isCollect){
      removeClass($$('.game .collect'),'disappear');
      addClass($$('.game .rank-notice'), 'disappear');
    }else{
      addClass($$('.game .collect'),'disappear');
      removeClass($$('.game .rank-notice'), 'disappear');
    }
  }
  
  /**
   * @param  {} client 
   * 三个值， 0 -> ios 1->android 2-> 都不是
   */
  getUserId(){
    var u = navigator.userAgent;
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
    var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    if(isAndroid){
      this.isAndroid =isAndroid;
      return window.control.getUserID();
    }else if(isiOS){
      this.isiOS = isiOS;
      window.webkit.messageHandler
    }else{
      console.log(this.userID);
      return this.userID;
    }
  }
  
}
window.setWebUserID = function(userID){
  const gs = new gameSelector();
  gs.userID = userID;
  gs.init();
}
function platform(){
  var u = navigator.userAgent;
  var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
  var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
  if(isAndroid){
    return 0;
  }else if(isiOS){
    return 1;
  }else{
    return 2;
  }
}
if(platform()!=1){
  const gs = new gameSelector();
  gs.init();
}
